package com.nancal.activiti.controller;

import com.github.pagehelper.Page;
import com.nancal.activiti.entity.Response;
import com.nancal.activiti.entity.pojo.ProcessUser;
import com.nancal.activiti.service.GroupService;
import com.nancal.activiti.service.UserService;
import com.nancal.common.core.controller.BaseController;
import com.nancal.common.core.page.TableDataInfo;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.activiti.engine.identity.UserQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/user")
public class ProcessUserController extends BaseController {
    @Autowired
    private UserService userService;
    @Autowired
    private IdentityService identityService;
    @Autowired
    private GroupService groupService;

    //id为组id
    @RequestMapping("/updateUser")
    public Response updateUser(@RequestBody ProcessUser user, @PathParam("groupId") String groupId) {
        System.out.println(groupId + user);
        userService.updateUser(user, groupId);
        return Response.success();
    }

    /**
     * 查询流程用户列表
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestBody HashMap<String, String> pageQuery) {
        String pageNum = pageQuery.get("pageNum");
        String pageSize = pageQuery.get("pageSize");
        System.out.println("***********************" + pageNum + pageSize);
      /*  PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();*/

        UserQuery userQuery = identityService.createUserQuery();

      /*  if (StringUtils.isNotBlank(query.getId())) {
            userQuery.userId(query.getId());
        }
        if (StringUtils.isNotBlank(query.getFirst())) {
            userQuery.userFirstNameLike("%" + query.getFirst() + "%");
        }
        if (StringUtils.isNotBlank(query.getEmail())) {
            userQuery.userEmailLike("%" + query.getEmail() + "%");
        }*/
        Integer pageNum1 = Integer.parseInt(pageNum);
        Integer pageSize1 = Integer.parseInt(pageSize);
        List<User> userList = userQuery.listPage((pageNum1 - 1) * pageSize1, pageSize1);
        Page<ProcessUser> list = new Page<>();
        list.setTotal(userQuery.count());
        list.setPageNum(pageNum1);
        list.setPageSize(pageSize1);

        for (User user : userList) {
            ProcessUser processUser = new ProcessUser();
            processUser.setId(user.getId());
            processUser.setFirst(user.getFirstName());
            processUser.setEmail(user.getEmail());
            // TODO: 2020/10/21 用户对应角色，一对多 还是一对一
            List<Group> groupsForUser = identityService.createGroupQuery().groupMember(user.getId()).list();
            String name = "";
            for (Group group : groupsForUser) {
                name = name + group.getName();
            }
            processUser.setGroupName(name);
            list.add(processUser);

        }

        return getDataTable(list);
    }

    //添加用户
    @PostMapping("/addUser")
    public Response addUser(@RequestBody Map<String, String> map) {
        Random random = new Random();
        int ran = random.nextInt(10000);
        String s = String.valueOf(ran);
        try {
            String email = map.get("email");
            String first = map.get("first");
            String last = map.get("last");
            String pwd = map.get("pwd");
            String groupId = map.get("groupId");
            User user = identityService.newUser(s);
            //将前端传来的姓赋值给User自带的姓
            user.setFirstName(first);
            //将前端传来的名赋值给User自带的名
            user.setLastName(last);
            //将前端传来的Email赋值给User自带的Email
            user.setEmail(email);
            //将前端传来的密码赋值给User自带的密码
            user.setPassword(pwd);
            //identityservice自带存贮User类
            identityService.saveUser(user);
            //利用identityService自带的创建关系绑定用户和组的关系
            identityService.createMembership(s, groupId);
            return Response.success();
        } catch (Exception e) {
            return Response.failure("请检查格式是否正确");
        }
    }


    //添加用户功能里显示角色
    @RequestMapping("/queryAllGroup")
    public Response queryAllGroup() {
        return Response.success(groupService.queryAllGroup());
    }
    //查询所有用户
    @RequestMapping("/queryAllUser")
    public Response queryAllUser(){
        return Response.success(userService.queryAllUser());
    }


    //根据名字查询用户
    @RequestMapping("/queryUserByName")
    public Response queryUser(@RequestBody ProcessUser processUser) {
        //获取前端传来的name
        //System.out.println(processUser.getFirst());
        ProcessUser myprocessUser = userService.queryUserByName(processUser.getFirst());
        System.out.println(myprocessUser);
        String id = myprocessUser.getId();
        //获取前端传来Myuser的id
        try {
            //利用identityService中的方法传入前端输入的id赋值给User自带id进行查询
            User user = identityService.createUserQuery().userId(id).singleResult();
            return Response.success(user);

        } catch (Exception e) {
            return Response.failure("请输入要查询的姓名");
        }
    }


    //解除 用户——组 关系   并     删除用户
    @RequestMapping("/delUser")
    public Response delUser(@RequestBody ArrayList<ProcessUser> processUsers) {
        try {
            //遍历集合遍历出的值是key
            for (int i = 0; i < processUsers.size(); i++) {

                //通过关系表查到所对应的value值
                List<Group> groups = identityService.createGroupQuery().groupMember(processUsers.get(i).getId()).list();
                if (groups != null) {
                    for (Group group : groups) {
                        String groupid = group.getId();
                        //根据key  value值解除关系
                        identityService.deleteMembership(processUsers.get(i).getId(), groupid);
                        //解除关系后根据id删除用户
                    }
                }
                identityService.deleteUser(processUsers.get(i).getId());
                //遍历value值
            }
            return Response.success();
        } catch (Exception e) {
            return Response.failure("解除失败,请联系管理员");
        }
    }

    //登录功能实现
    @RequestMapping("/login")
    public Response login(@RequestBody ProcessUser processUser) {
        //从前端数据获取账号信息
        String myEmail = processUser.getEmail();
        try {
            //利用Activiti定义好的方法来调用查询功能（参数是上面获取打到的账号信息中的账号）
            User user = identityService.createUserQuery().userEmail(myEmail).singleResult();
            //登录判断【如果密码不为空而且密码跟从数据库中获取的密码相同】
            if (processUser.getPwd() != null && processUser.getPwd().equals(user.getPassword())) {
                //为了在前端显示不出密码
                user.setPassword("");
                //返回登录成功（参数是User对象）
                return Response.success(user);

            } else {
                return Response.failure("请确认账号或密码是否有误");
            }
        } catch (NullPointerException exception) {
            return Response.failure("请检查账号或先注册");
        }
    }
}